import React from 'react';
import _ from 'underscore';
import moment from 'moment';
import format from 'lib/util/format'

import {Scope} from 'lib/scopeFactory';
import TimeStore from 'lib/stores/time-store'

import basicInfo from '../apis/basicInfo';
import {propConfig, coreApi, parseToTopbar} from '../apis/core-util';
// import {imsiApi,createGridOrder,parseToPartIMSIGrid} from '../apis/imsi-grid-util';
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'

export default class DrillScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.domainId = props.routeParams.domainId;
    this.urlId = props.routeParams.urlId;
    this.requestTime = props.routeParams.requestTime;

    this.$state = {
      title:'',
      traceType:props.routeParams.traceType,
      basicInfo:{},
      pie0:{
        loading:true
      }
      ,pie1:{
        loading:true
      }
      ,pie2:{
        loading:true
      }
      ,dataOffset:1
      ,dataGrid:{
        loading:true
      }
      ,userInfoGrid:{
        loading:true,
        getOrder:createGridOrder('timestamp', -1)
      }
      ,userInfoCols:
      [{
        title:'用户信息',
        key:'userName',
        sortable:true,
        render:function(fmtVal,rowData){
          return (
            <a href={
              BlueWare.pageUrlPrefix+'/app/'+BlueWare.appId+'/imsisearch'+'#/trace/webview/'+rowData.appVersionId+'/'+rowData.deviceId+'/'+encodeURIComponent(rowData.userIdentifier)+'/'+rowData.dataType+'/'+rowData.domainId+'/'+rowData.urlId
            }>{rowData.userIdentifier}</a>
          )
        }
      },{
        title:'设备信息',
        key:'model',
        sortable:true,
        render:function(fmtVal,rowData){
          return (
            <span>{rowData.manufacturer}</span>
          )
        }
      },{
        title:'APP版本',
        key:'appVersion',
        sortable:true
      },{
        title:'采集次数',
        key:'totalNum',
        sortable:true
      },{
        title:'Ajax请求采集时间',
        key:'timestamp',
        sortable:true,
        formatter:format.stampToTime
      }]
    } // $state

    this.$state.pieChartSettings = {
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        x: -50,
        navigation: {
          animation: true
        }
      },
      plotOptions: {
        pie: {
          dataLabels: {
            enabled: false
          },
          showInLegend: true
        }
      }
    };

    this.basicInfoApi = basicInfo({
      id:this.urlId,
      parentId:this.domainId,
      urlName:'url'
    });

    this.pie0Api = coreApi({
      size:1,
      limit:9,
      offset:0,
      traceType:1,
      urlId:this.urlId,
      classify:'statuscode',
      domainId:this.domainId,
      urlName:'ajax/ajaxchart'
    },TimeStore.getValue, () => this.requestTime);

    this.pie1Api = coreApi({
      size:1,
      limit:9,
      offset:0,
      traceType: this.$state.traceType === 'error' ? 1 : 2,
      urlId:this.urlId,
      classify:'region',
      domainId:this.domainId,
      urlName:'ajax/ajaxchart'
    },TimeStore.getValue, () => this.requestTime);

    this.pie2Api = coreApi({
      size:1,
      limit:9,
      offset:0,
      traceType: this.$state.traceType === 'error' ? 1 : 2,
      urlId:this.urlId,
      classify:'networkgeneration',
      domainId:this.domainId,
      urlName:'ajax/ajaxchart'
    },TimeStore.getValue, () => this.requestTime);

    this.requestApi = coreApi({
      size:1,
      limit:1,
      offset:0,
      order:301,
      urlId:this.urlId,
      domainId:this.domainId,
      urlName:'ajax/ajaxtracelist',
      traceType:this.$state.traceType === 'slow' ? 2 : 1
    }, TimeStore.getValue, () => this.requestTime);

    this.dataGridApi = coreApi({
      urlId:this.urlId,
      domainId:this.domainId,
      size: 1,
      limit: 1,
      offset:()=>this.$state.dataOffset - 1,
      urlName:()=>`ajax/${this.$state.traceType}ajaxdetail`
    },TimeStore.getValue, () => this.requestTime);

    this.userInfoApi = tracelistApi({
      urlName:'custom/affected_users',
      domainId:this.domainId,
      urlId:this.urlId,
      limit:10,
      crashNameId:this.crashtraceId,
      dataType:this.$state.traceType === 'error'?7:8 // 7:ajaxError,8:ajaxTrace
    },TimeStore.getValue,this.$state.userInfoGrid.getOrder,function(){
      return {
        appVersionId:this.$state.dataGrid.data?this.$state.dataGrid.data.appVersionId:undefined
      }
    }.bind(this));

  } // constructor

  fetchBasicInfo() {
    this.basicInfoApi
        .fetch()
        .fail(()=>this.$state.title = '')
        .done((data,params)=>this.$state.title = data.result[0].name)
        .always(()=>this.emit());

    this.requestApi
        .fetch()
        .progress(()=>{
          this.$state.basicInfo = {};
          this.emit();
        })
        .done(data=>{
          let item = data.ajaxTraceListResults[0];
          this.$state.basicInfo = {
            lastTime:moment(item.lastTime).format('YYYY-MM-DD HH:mm'),
            count:format.integer(item.count),
            avgTimeForResponse:format.numSecs(item.avg)
          }
        })
        .always(()=>this.emit());
  } // fetchBasicInfo

  fetchPie0() {
    this.pie0Api
        .fetch()
        .progress(()=>{
          this.$state.pie0 = {
            loading:true
          };
          this.emit();
        })
        .fail(error=>this.$state.pie0 = {error})
        .done(data=>{
          this.$state.pie0 = {
            data:{
              series:_.map(data.ajaxChartResults, item=>({
                id:item.id,
                name:item.name,
                data:[{
                  y:item.count,
                  customData:{
                    y:{
                      label:item.name,
                      fmtVal:item.count
                    },
                    startTime:data.startTime,
                    endTime:data.endTime
                  }
                }]
              }))
            }
          };
        })
        .always(()=>this.emit());
  } // fetchPie0

  fetchPie1() {
    this.pie1Api
        .fetch()
        .progress(()=>{
          this.$state.pie1 = {
            loading:true
          };
          this.emit();
        })
        .fail(error=>this.$state.pie1 = {error})
        .done(data=>{
          this.$state.pie1 = {
            data:{
              series:_.map(data.ajaxChartResults, item=>({
                id:item.id,
                name:item.name,
                data:[{
                  y:item.count,
                  customData:{
                    y:{
                      label:item.name,
                      fmtVal:item.count
                    },
                    startTime:data.startTime,
                    endTime:data.endTime
                  }
                }]
              }))
            }
          };
        })
        .always(()=>this.emit());
  } // fetchPie1

  fetchPie2() {
    this.pie2Api
        .fetch()
        .progress(()=>{
          this.$state.pie2 = {
            loading:true
          };
          this.emit();
        })
        .fail(error=>this.$state.pie2 = {error})
        .done(data=>{
          this.$state.pie2 = {
            data:{
              series:_.map(data.ajaxChartResults, item=>({
                id:item.id,
                name:item.name,
                data:[{
                  y:item.count,
                  customData:{
                    y:{
                      label:item.name,
                      fmtVal:item.count
                    },
                    startTime:data.startTime,
                    endTime:data.endTime
                  }
                }]
              }))
            }
          };
        })
        .always(()=>this.emit());
  } // fetchPie2

  fetchDataGrid() {
    this.dataGridApi
        .fetch()
        .progress(()=>{
          this.$state.dataGrid = {loading:true};
          this.emit();
        })
        .fail(error=>this.$state.dataGrid={error})
        .done(data=>this.$state.dataGrid={data})
        .always(()=>this.emit());
  } // fetchDataGrid

  fetchUserInfo(force){
    var _this = this;
    // console.log('_this', _this);
    if((force&&this.$state.userInfoGrid.data)||(!force&&!this.$state.userInfoGrid.data)){
      this.userInfoApi.fetch().then((rawData,params) => {
        // _this.$state.userInfoGrid = parseToPartIMSIGrid(_.map(rawData.data, item => {
        _this.$state.userInfoGrid = parseToPartGrid(_.map(rawData, item => {
          item.dataType = _this.$state.traceType === 'error' ? 'ajaxError' : 'ajaxTrace';
          item.domainId = _this.domainId;
          item.urlId = _this.urlId;
          return item
        }), params);
        _this.emit()
      })
    }
  } // fetchUserInfo

  fetch() {
    this.fetchBasicInfo();
    if (this.$state.traceType === 'error') {
      this.fetchPie0();
    }
    this.fetchPie1();
    this.fetchPie2();
    this.fetchDataGrid();
    this.fetchUserInfo(true);
  } // fetch

  $select_indexed_value(payload) {
    this.$state.dataOffset = payload.index;
    this.fetchDataGrid();
  } // $select_indexed_value

  $settime(payload){
    this.fetch();
  } // $settime

  $load() {
    this.fetch();
  } // $load
}
